<template>
    <BPTable ref='tableRef' align='center' row-key='id' :columns='columns' :api='page' :buttons='buttons' :rowSelection="false">
    </BPTable>

    <BDialog v-model:visible='visible' :title='dialogTitle' width='600px' :confirm='submit' @close="resetForm">
        <a-form ref='formRef' layout="vertical" :model='formData'>
            <a-form-item style='display:none' name='id'>
                <a-input type='hidden' v-model:value='formData.id' />
            </a-form-item>
            <a-form-item label="名称" name='name' :rules="[{required : true, message : '请输入名称'}]">
                <a-input type='text' v-model:value='formData.name' />
            </a-form-item>
            <template v-for="(row, index) in deviceParamsRules" :key="index">
                <a-row :gutter="24">
                    <a-col v-for="item in row" :key="item.key" :span="12">
                        <a-form-item :label="item.name" required :name="['params', item.key]">
                            <a-input type="number" v-model:value='formData.params[item.key]' :addonAfter="item.unit" />
                        </a-form-item>
                    </a-col>
                </a-row>
                
            </template>
            <a-form-item :label="$c('remark')" name="remark">
                <a-input v-model:value='formData.remark' />
            </a-form-item>
        </a-form>
    </BDialog>

</template>

<script lang='ts' setup>
    import { pageApi, deleteApi, saveApi } from '@/api/devices/Params'
    import { dictionaryItemByCategoryApi } from '@/api/system/Dictionary'
    import { useI18nStore } from '@/store/i18n'
    import { message, Modal } from 'ant-design-vue'
    import { ref } from 'vue'

    import DeviceParamsRule from '@/models/DeviceParamsRule'

    const deviceParamsRules = ref<any[][]>([])
    for(let i = 0; i < DeviceParamsRule.length; i += 2) {
        if(DeviceParamsRule[i]) {
            let row:any[] = [DeviceParamsRule[i]]
            if(DeviceParamsRule[i + 1]) {
                row.push(DeviceParamsRule[i + 1])
            }

            deviceParamsRules.value.push(row)
        }
    }


    const i18n = useI18nStore()
    const visible = ref(false)

    const tableRef = ref()
    const formRef = ref()
    const dialogTitle = ref()
    
    const dataTypes = ref<any[]>([]) //数据类型
    dictionaryItemByCategoryApi('DATA_TYPE').then(res => {
        dataTypes.value = res.data
    })

    const formData = ref<{id:number,name:string, remark:string, params:{[key:string] : number}}>({
        id : 0,
        name : '',
        params : {},
        remark : ''
    })

    

    

    const buttons = ref<SearchButton[]>([])
    buttons.value.push({
        button : 'add',
        func : () => {
            dialogTitle.value = i18n.t('add')
            
            formData.value.params = {}
            


            visible.value = true
        }
    })


  
    function resetForm() {
        formRef.value.clearValidate()
        formRef.value.resetFields()
    }
    
    async function submit() {
        let { id, ...params} = await formRef.value.validate()
        
        if(id) {
            params.id = Number(id)
        }

        for(let k in params.params) {
            params.params[k] = Number(params.params[k])
        }


        const res = await saveApi(params)
        if(res.success) {
            resetForm()
            visible.value = false
            message.success(i18n.t('saveSuccess'))
            tableRef.value.load()
        }else {
            Modal.error({
                title : res.msg
            })
        }
    }


    async function page(params) {
        const res = await pageApi(params)
      
        if(res.data) {
            res.data.rows.forEach(row => {
                if(row.params) {
                    for(let k in row.params) {
                        row[k] = row.params[k]
                    }
                }

            })
        }

        return res
    }
    

    const columns = ref<Column[]>([
        {
            title : i18n.t('name'),
            dataIndex : 'name',
            align : 'center',
            translate : true,
            inSearch : true
        },

        ...(
            DeviceParamsRule.map(item => {
                return {
                    title : item.name + `(${item.unit})`,
                    dataIndex : item.key,
                    align : 'center',
                }
            })
        ),

        {
            title : i18n.t('remark'),
            dataIndex : 'remark',
            align : 'center',
        },

        {
            title : i18n.t('action'),
            dataIndex : '$action',
            align : 'center',
            $edit : (row) => {
                dialogTitle.value = i18n.t('edit')
                for(let k in formData.value) {
                    formData.value[k] = row[k]
                    
                }
                // formFields.forEach(field => {
                //     if(field.name == 'expireIn') {
                //         field.defaultValue = row[field.name] ? dayjs(row[field.name] * 1000) : ''
                //     }else {
                //         field.defaultValue = row[field.name]
                //     }
                    
                // })

                visible.value = true
            },

            $delete :  async (row) => {
                const res = await deleteApi(row.id)
                if(res.success) {
                    message.success(i18n.t('deleteSuccess'))
                    tableRef.value.load()
                }else {
                    message.error(res.msg)
                }
            }
        }
    ])


    

    
</script>

<style lang='scss' module>
    .username{
        display: inline-flex;
        align-items: center;
        gap: 10px;
    }
</style>